<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';
import { bookAPI } from '../api';
import { useDataStore } from '../stores';

const store = useDataStore()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const searchKeyword = ref('')
const form = ref({
  title: '',
  author: '',
  publisher: '',
  price: '',
  stock: ''
})
const isEdit = ref(false)

const rules = ref({
  title: [
    { required: true, message: '请输入图书名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  publisher: [
    { required: true, message: '请输入出版社', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur' },
    { type: 'number', message: '库存必须为数字', trigger: 'blur' }
  ]
})

const formRef = ref(null)

// 加载图书数据
const loadBooks = async () => {
  await store.fetchBooks(searchKeyword.value)
}

// 搜索处理函数
const handleSearch = () => {
  loadBooks()
}

// 重置搜索
const handleReset = () => {
  searchKeyword.value = ''
  loadBooks()
}

onMounted(() => {
  loadBooks()
})

const handleAdd = () => {
  dialogTitle.value = '新增图书'
  isEdit.value = false
  form.value = {
    title: '',
    author: '',
    publisher: '',
    price: '',
    stock: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑图书'
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该图书吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await bookAPI.delete(row.id)
      ElMessage.success('删除成功')
      loadBooks()
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }).catch(() => {})
}

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    if (isEdit.value) {
      await bookAPI.update(form.value.id, form.value)
      ElMessage.success('编辑成功')
    } else {
      await bookAPI.create(form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    loadBooks()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
    }
    console.error(error)
  }
}
</script>

<template>
  <div class="books-container">
    <div class="header">
      <h2>图书管理</h2>
      <div class="header-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索书名/作者/出版社"
          style="width: 300px; margin-right: 10px"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <span>搜索</span>
            </el-button>
          </template>
        </el-input>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="handleAdd">新增图书</el-button>
      </div>
    </div>

    <el-table :data="store.books" style="width: 100%" v-loading="store.loading">
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="title" label="书名" width="200" />
      <el-table-column prop="author" label="作者" width="150" />
      <el-table-column prop="publisher" label="出版社" width="200" />
      <el-table-column prop="price" label="价格" width="150">
        <template #default="{ row }">
          ¥{{ row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" min-width="150" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="书名" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" />
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="form.publisher" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" :precision="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.books-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 添加表格样式 */
:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-header-bg-color: var(--el-fill-color-light);
  --el-table-row-hover-bg-color: var(--el-fill-color);
  border-spacing: 0;
}

:deep(.el-table td.el-table__cell) {
  padding: 8px 0;
}

:deep(.el-table .cell) {
  padding: 0 8px;
  white-space: nowrap;
}
</style> 